//
//  RMMChooseRegionViewController.m
//  Romomo
//
//  Created by puman on 16/10/8.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMChooseRegionViewController.h"
#import "RMMRegionTableViewCell.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "RMMRegionView.h"
#import "RMMNagationView.h"

@interface RMMChooseRegionViewController ()<UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>

@property(nonatomic,strong)CLLocationManager  *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;

@end

@implementation RMMChooseRegionViewController
{
    UITableView *_tableView;
    NSArray *_regionArray;
    RMMRegionView *_regionView;
    RMMNotNetWorkView *_networkView;
}
- (CLGeocoder *)geocoder {
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}
- (CLLocationManager *)locationManager {
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        // 创建同时设置代理为self
        _locationManager.delegate = self;
    }
    return _locationManager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.navigationItem.title = @"选择地区";
    [self addViews];
    [self getData];
   // [self openLacotion];
    // Do any additional setup after loading the view.
}
- (void)close{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)getData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    NSString *url = GetRegionUrl;
    [OSRequestManager requestWithUrlString:url parDic:nil network:^(BOOL isNetwork) {
        if (!isNetwork) {
            _networkView.hidden = NO;
        } else {
            _networkView.hidden = YES;
        }

    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _regionArray = dataDic[@"data"];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];

    } error:^(NSError *errors) {
        _networkView.hidden = NO;
    } view:self.view];
}
- (void)addViews{
    RMMNagationView *naView = [[RMMNagationView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 64)];
    BUTTON_S(naView.backButton, close);
    [self.view addSubview:naView];
//  
//    _regionView = [[RMMRegionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 93)];
    
    UIView *fView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, naView.bottom, kScreenWideth, kScreenHeight - naView.bottom) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = fView;
    _tableView.separatorColor = RGBA(221, 221, 221, 1);
    [_tableView registerClass:[RMMRegionTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
   // [self addTableViewFootView];
    
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];
}
- (void)networkBut{
    [self getData];
}

- (void)addTableViewFootView{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 70)];
    footView.backgroundColor = kWhiteColor;
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        _tableView.tableFooterView = footView;
    } else {
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
 
    }

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 12, kScreenWideth, 14)];
    label.font = kBFont(13);
    label.textColor = COLORFROMCODE(0x9B9B9B, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"为了更多的提供服务,请允许容么么定位";
    [footView addSubview:label];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(kScreenWideth / 2 - 60, label.bottom + 9, 120, 40);
    BUTTON_S(button, openLacotion);
    button.layer.borderColor = COLORFROMCODE(0x53C7C6, 1).CGColor;
    button.layer.borderWidth = 1;
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = kMaric;
    [button setTitleColor:COLORFROMCODE(0x53C7C6, 1) forState:(UIControlStateNormal)];
    [button setTitle:@"开启定位" forState:(UIControlStateNormal)];
    [footView addSubview:button];
}
// 开启定位
- (void)openLacotion{
    [self addAlertController];
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        [self addAlertController];
    }
    [self openMap];
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    return _regionView;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 93;
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _regionArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kHalf -1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RMMRegionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    // cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.cityName = _regionArray[indexPath.row][@"ORG_NAME"];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  //  [[RMMFileManager shareHandle] saveVale:_regionArray[indexPath.row] forKey:@"currentCity"];
    _currentCity(_regionArray[indexPath.row][@"ORG_NAME"],_regionArray[indexPath.row][@"REGION_ID"]);
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark --------------------定位-----------------------
- (void)openMap{
     if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0) {
            [self.locationManager requestWhenInUseAuthorization];
        }
        
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
    }
    [self.locationManager startUpdatingLocation];
}
- (void)addAlertController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请允许容么么获取你的当前位置" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *setlAction = [UIAlertAction actionWithTitle:@"去设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:setlAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations firstObject];
    
    //    NSLog(@"%@", location);
    NSString *latitudeStr = [NSString stringWithFormat:@"%.2lf", location.coordinate.latitude];
    NSString *longitudeStr = [NSString stringWithFormat:@"%.2lf", location.coordinate.longitude];
    
    [self getCityNameWithLatitude:latitudeStr longitude:longitudeStr];
    
}
// 反地理编码: 经纬度坐标->地名
- (void)getCityNameWithLatitude:(NSString *)latitudeStr longitude:(NSString *)longitudeStr
{
    if (latitudeStr.length == 0 || longitudeStr.length == 0) {
        return;
    }
    CLLocationDegrees latitude = [latitudeStr doubleValue];
    CLLocationDegrees longitude = [longitudeStr doubleValue];
    // 根据经纬度创建location对象.
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (error || placemarks.count == 0) {
        } else {
            // 编码成功
            CLPlacemark *placemark = [placemarks firstObject];
            _regionView.cityName = placemark.locality;
            _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
            [_tableView reloadData];
        }
    }];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    [self addTableViewFootView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
